﻿namespace Sustainalytics.PdfGeneration.Service.Filters
{
    using System;
    using System.Net;
    using System.Threading;
    using System.Web.Http.Filters;
    using Sustainalytics.ReportGenerator.BL;
    using Sustainalytics.Utils.Configuration;

    public sealed class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private readonly LogAggregator _log;

        public CustomExceptionFilterAttribute(LogAggregator log)
        {
            this._log = log;
        }

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var errorMessage = actionExecutedContext.Exception.Message;

            actionExecutedContext
                .SetErrorResponseFor<OperationCanceledException>(HttpStatusCode.NoContent, errorMessage)
                .SetErrorResponseFor<Exception>(HttpStatusCode.InternalServerError, actionExecutedContext.Exception.ToString());

            if (actionExecutedContext.Exception.GetType() != typeof(OperationCanceledException))
            {
                this._log.LogError(actionExecutedContext.Exception.ToString());
                Startup.IsGenerationRunning = false;
                Startup.Token.Dispose();
                Startup.Token = new CancellationTokenSource();
                Startup.TtlManager = new TTLManager(SettingsHelper.Read("TimeToLive", 60 * 60 * 1000));
                Startup.TtlManager.Start();
            }
        }
    }
}
